package fr.uhp.mpr.tools;

import java.net.URL;
import java.net.URLConnection;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Scanner;

import fr.uhp.mpr.data.DataMeter;
import fr.uhp.mpr.data.Intervalle;
import fr.uhp.mpr.data.DataMeter.iname;

public class CurrentDataProvider {

	private final String adress = "http://www.meteometz.com/wswin/aktuell.htm";
	private static final String END_OF_INPUT = "\\Z";
	  
	private URL url;
	private String page;
	
	private Intervalle temperature;
	private Intervalle humidite;
	private Intervalle pression;
	private Intervalle vent;
	
	public CurrentDataProvider(){
		try{
			url = new URL(adress);
		    URLConnection connection = null;
		    connection =  url.openConnection();
		    Scanner scanner = new Scanner(connection.getInputStream());
		    scanner.useDelimiter(END_OF_INPUT);
		    page = scanner.next();
		}catch(Exception e){
			e.printStackTrace();
		}
		
		extract();
	}
	
	private void extract(){
		String[] lines = page.split("\n");
		int count = 0;
		
		CharSequence chs = "<nobr>"+(new SimpleDateFormat("dd/MM/yyyy").format(new Date()))+"</nobr>";
		while(!lines[count].contains(chs))
			count++;
		
		temperature = DataMeter.matchIntervalle(lines[count+2].replace(",",".").replace("<td><nobr>","").replace("</nobr></td>","").split(" ")[0],DataMeter.getIntervalle(iname.TEMPERATURE));
		humidite = DataMeter.matchIntervalle((Double.valueOf(lines[count+3].replace(",",".").replace("<td>","").replace("</td>","").split(" ")[0]).doubleValue()/100)+"",DataMeter.getIntervalle(iname.HUMIDITY));
		pression = DataMeter.matchIntervalle(lines[count+4].replace(",",".").replace("<td><nobr>","").replace("</nobr></td>","").split(" ")[0],DataMeter.getIntervalle(iname.PRESSURE));
		vent = DataMeter.matchIntervalle(lines[count+6].replace(",",".").replace("<td><nobr>","").replace("</nobr></td>","").split(" ")[0],DataMeter.getIntervalle(iname.WIND));
		
	}

	public Intervalle getTemperature() {
		return temperature;
	}

	public Intervalle getHumidite() {
		return humidite;
	}

	public Intervalle getPression() {
		return pression;
	}

	public Intervalle getVent() {
		return vent;
	}

	@Override
	public String toString() {
		return "CurrentDataProvider [humidite=" + humidite + ", pression="
				+ pression + ", temperature=" + temperature + ", vent=" + vent
				+ "]";
	}
	
	
	
}
